package com.sinheldrin.musicplayer.reader
{
	import com.sinheldrin.musicplayer.library.Library;
	import com.sinheldrin.musicplayer.music.Music;
	import com.sinheldrin.musicplayer.music.Playlist;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLLoader;
	import flash.net.URLRequest;

	public class XmlReader extends EventDispatcher implements IReader
	{
		public function XmlReader()
		{
		}
		
		public function readLibrary(library:Library, file:File):void
		{
			var fileStream:FileStream = new FileStream();
			fileStream.open(file, FileMode.READ);
			var xml:XML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
			for each (var musicXml:XML in xml.musics.music)
			{
				library.addMusic(parseMusic(musicXml));
			}
			fileStream.close();
		}
		
		public function read():Playlist
		{
			var file:File = File.desktopDirectory.resolvePath("test.xml");
			var fileStream:FileStream = new FileStream();
			fileStream.open(file, FileMode.READ);
			var xml:XML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
			var playlist:Playlist = parseXml(xml);
			fileStream.close();
			return playlist;
		}
		
		private function parseXml(xml:XML):Playlist
		{
			var playlist:Playlist = new Playlist();
			
			for each (var musicXml:XML in xml.musics.music)
			{
				playlist.addMusic(parseMusic(musicXml));
			}
			
			return playlist;
		}
		
		private function parseMusic(xml:XML):Music
		{
			var music:Music = new Music();
			music.id = xml.@id;
			music.VideoId = xml.@video_id;
			music.author = xml.@author;
			music.title = xml.@title;
			return music;
		}
	}
}